<?php

namespace app\http\middleware;
use think\Controller;
use think\Db;
use app\model\Mch;
/**
 * Undocumented 商户后台中间键
 */
class Merchants extends Controller
{
    public function handle($request, \Closure $next)
    {
        if(get_is_ip() === false){
            Session("auth_mch",null);
            return $this->error('该IP已列入黑名单','/web/login');
        }
        $redis = new \Predis\Client();
        if($redis->get('web') == 1){
            Session("auth_mch",null);
            return $this->error('网站维护中。。。。。','/web/login');
        }
        $auth_mch = Session("auth_mch");
        if(!$auth_mch){
            return $this->error('登录超时,请重新登录','/web/login');
        }
        $mch = Mch::get_mch($auth_mch['mch']);
        //单点登录
        if($auth_mch['secret_key'] != $mch->secret_key){
            Session("auth_mch",null);
            return $this->error('该账号已在别处登陆','/web/login');
        }
        //绑定谷歌
        if(empty($mch->googl_secret)){
            //get_google('/web/google',$auth_mch['mch']);
        }
        if($mch->status == 2){
            Session("auth_mch",null);
            return $this->error('账号已禁用，请联系管理员解禁','/web/login');
        }
        $role_id = $auth_mch['is_agent'] == 1 ? '6' : '7';//角色id
        if(empty($role_id)){
            return $this->error('角色不存在','/web/login');
        }
        //获取当前路由
        $url = rtrim(str_replace('//','',strip_tags($request->routeInfo()['rule'])),'/');
        if($url != 'web' && $url !="web/welcome" && $url !="web/home"){
            //当前菜单id是否在当前角色里面
            if(!in_array(__menu([$url],2),explode(",",$this->get_role($role_id)))){
                return $this->error("权限不够");
            }
        }
        $this->assign("menu",getTree(__menu($this->get_role($role_id),2,2)));//菜单
        $this->assign('auth_mch',$mch);
        $request->auth_mch = $auth_mch;
        return $next($request);
    }
    /**
     * Undocumented 获取当前账号角色权限id
     *
     * @param [type] $id
     * @return void
     */
    public function get_role($id){
       
        $info = get_one('role',$id);
       
        if(!empty($info)){
            return $info['action'];
        }
        return Role::where("id",$id)->value("action");
    }
   
}
